/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { useRef, useState } from 'react' // 引入react的useRef
import { formatSecondsToTime } from '../../../../utils/index' // 时间格式化


/* ts类型 */

// 进度条组件的props
interface MusicProgressProps {
  currentTime: number;
  duration: number;
  percent: number,
  onChildClickProgress: (event: any) => void;
}

/* 音频进度条 */
const MusicProgress: React.FC<MusicProgressProps> = ({ duration, percent, currentTime, onChildClickProgress }) => {

  /* 声明变量 */
  const [isDragging, setIsDragging] = useState(false) // 是否正在拖拽
  const progressBarRef = useRef(null) // 进度条组件的ref
  const activeRef = useRef(null) // 进度条组件的ref
  const dragRef = useRef(null) // 进度条组件的ref

  /* 事件函数 */
  // 计算进度条的位置
  const calculateProgress = (clientX:number) => {
    if (!progressBarRef.current) return;
    const progressBar: any = progressBarRef.current;
    const rect = progressBar.getBoundingClientRect();
    const offsetX = clientX - rect.left;
    const progressBarWidth = progressBar.offsetWidth;
    let newProgress = (offsetX / progressBarWidth) * 100;
    newProgress = Math.max(0, Math.min(100, newProgress));
    return newProgress
  };
  // 鼠标按下
  const handleMouseDown = (event: any) => {
    setIsDragging(true);
    const progress = calculateProgress(event.touches[0].clientX);
    onChildClickProgress(progress)
  };
  // 开始拖拽
  const handleMouseMove = (event: any) => {
    console.log(event);
    if (isDragging) {
      const progress = calculateProgress(event.touches[0].clientX);
      onChildClickProgress(progress)
    }
  };
  // 结束拖拽
  const handleMouseUp = () => {
    setIsDragging(false);
  };
  // 直接更新进度条位置
  const handleClickProgress = (event: any) => {
    const clientX = event.clientX || event.touches[0].clientX;
    const progress = calculateProgress(clientX );
    onChildClickProgress(progress)
  }
  
  return (
    <>
      <div className='Progress'>
        <span>{formatSecondsToTime(currentTime)}</span>
        <div className='Progress-content' ref={progressBarRef} onClick={handleClickProgress}>
          <div className='Progress-text'>
            <div ref={activeRef} className='active-color' style={{width:`${percent}%`}}></div>
            <div ref={dragRef} className='drag'  style={{ left: `${percent}%` }} onTouchStart={handleMouseDown} onTouchMove={handleMouseMove} onTouchEnd={handleMouseUp}></div>
          </div>
        </div>
        <span>{formatSecondsToTime(duration)}</span>
      </div>
    </>
  )
}


export default MusicProgress